import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Link } from 'react-router-dom';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  FunnelIcon,
  EllipsisVerticalIcon,
  PencilIcon,
  TrashIcon,
  ClipboardDocumentListIcon,
  CheckCircleIcon,
  ClockIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';
import toast from 'react-hot-toast';

const Tasks = () => {
  const [filters, setFilters] = useState({
    status: '',
    priority: '',
    search: '',
  });
  const [showFilters, setShowFilters] = useState(false);
  const queryClient = useQueryClient();

  // 获取任务列表
  const { data: tasksData, isLoading } = useQuery(
    ['tasks', filters],
    () => api.get('/tasks/my-tasks', { params: filters }),
    {
      keepPreviousData: true,
    }
  );

  // 更新任务状态
  const updateStatusMutation = useMutation(
    ({ taskId, status }) => api.put(`/tasks/${taskId}/status`, { status }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('tasks');
        toast.success('任务状态更新成功');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '更新失败');
      },
    }
  );

  // 删除任务
  const deleteTaskMutation = useMutation(
    (taskId) => api.delete(`/tasks/${taskId}`),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('tasks');
        toast.success('任务删除成功');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '删除失败');
      },
    }
  );

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleStatusUpdate = (taskId, newStatus) => {
    updateStatusMutation.mutate({ taskId, status: newStatus });
  };

  const handleDeleteTask = (taskId) => {
    if (window.confirm('确定要删除这个任务吗？')) {
      deleteTaskMutation.mutate(taskId);
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'done':
        return <CheckCircleIcon className="h-5 w-5 text-success-500" />;
      case 'in_progress':
        return <ClockIcon className="h-5 w-5 text-warning-500" />;
      case 'overdue':
        return <ExclamationTriangleIcon className="h-5 w-5 text-danger-500" />;
      default:
        return <ClockIcon className="h-5 w-5 text-gray-400" />;
    }
  };

  const getPriorityColor = (priority) => {
    switch (priority) {
      case 'urgent':
        return 'priority-urgent';
      case 'high':
        return 'priority-high';
      case 'medium':
        return 'priority-medium';
      case 'low':
        return 'priority-low';
      default:
        return 'priority-medium';
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'done':
        return 'status-done';
      case 'in_progress':
        return 'status-in-progress';
      case 'review':
        return 'status-review';
      case 'cancelled':
        return 'status-cancelled';
      default:
        return 'status-todo';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'todo':
        return '待办';
      case 'in_progress':
        return '进行中';
      case 'review':
        return '审核中';
      case 'done':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return status;
    }
  };

  const getPriorityText = (priority) => {
    switch (priority) {
      case 'low':
        return '低';
      case 'medium':
        return '中';
      case 'high':
        return '高';
      case 'urgent':
        return '紧急';
      default:
        return priority;
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  const tasks = tasksData?.data?.tasks || [];

  return (
    <div className="space-y-6">
      {/* 页面标题和操作 */}
      <div className="sm:flex sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">任务管理</h1>
          <p className="mt-1 text-sm text-gray-500">
            管理您的任务，跟踪进度和截止日期
          </p>
        </div>
        <div className="mt-4 sm:mt-0">
          <Link
            to="/tasks/new"
            className="btn-primary"
          >
            <PlusIcon className="h-4 w-4 mr-2" />
            创建任务
          </Link>
        </div>
      </div>

      {/* 搜索和筛选 */}
      <div className="card">
        <div className="card-body">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-4 sm:space-y-0">
            <div className="flex-1 max-w-lg">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  type="text"
                  placeholder="搜索任务..."
                  className="input pl-10"
                  value={filters.search}
                  onChange={(e) => handleFilterChange('search', e.target.value)}
                />
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="btn-outline"
              >
                <FunnelIcon className="h-4 w-4 mr-2" />
                筛选
              </button>
            </div>
          </div>

          {/* 筛选选项 */}
          {showFilters && (
            <div className="mt-4 pt-4 border-t border-gray-200">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700">状态</label>
                  <select
                    className="mt-1 input"
                    value={filters.status}
                    onChange={(e) => handleFilterChange('status', e.target.value)}
                  >
                    <option value="">全部状态</option>
                    <option value="todo">待办</option>
                    <option value="in_progress">进行中</option>
                    <option value="review">审核中</option>
                    <option value="done">已完成</option>
                    <option value="cancelled">已取消</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">优先级</label>
                  <select
                    className="mt-1 input"
                    value={filters.priority}
                    onChange={(e) => handleFilterChange('priority', e.target.value)}
                  >
                    <option value="">全部优先级</option>
                    <option value="low">低</option>
                    <option value="medium">中</option>
                    <option value="high">高</option>
                    <option value="urgent">紧急</option>
                  </select>
                </div>
                <div className="flex items-end">
                  <button
                    onClick={() => setFilters({ status: '', priority: '', search: '' })}
                    className="btn-outline w-full"
                  >
                    清除筛选
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 任务列表 */}
      <div className="card">
        <div className="card-body p-0">
          {tasks.length > 0 ? (
            <div className="divide-y divide-gray-200">
              {tasks.map((task) => (
                <div key={task.id} className="p-6 hover:bg-gray-50">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(task.status)}
                        <h3 className="text-lg font-medium text-gray-900">
                          {task.title}
                        </h3>
                        <span className={`status-badge ${getStatusColor(task.status)}`}>
                          {getStatusText(task.status)}
                        </span>
                        <span className={`priority-badge ${getPriorityColor(task.priority)}`}>
                          {getPriorityText(task.priority)}
                        </span>
                      </div>
                      {task.description && (
                        <p className="mt-2 text-sm text-gray-600">{task.description}</p>
                      )}
                      <div className="mt-3 flex items-center space-x-4 text-sm text-gray-500">
                        {task.project && (
                          <span>项目: {task.project.name}</span>
                        )}
                        {task.due_date && (
                          <span>
                            截止: {new Date(task.due_date).toLocaleDateString()}
                          </span>
                        )}
                        {task.assignee && (
                          <span>分配给: {task.assignee.username}</span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      {task.status !== 'done' && (
                        <button
                          onClick={() => handleStatusUpdate(task.id, 'done')}
                          className="text-success-600 hover:text-success-700"
                          title="标记为完成"
                        >
                          <CheckCircleIcon className="h-5 w-5" />
                        </button>
                      )}
                      <button
                        onClick={() => handleDeleteTask(task.id)}
                        className="text-danger-600 hover:text-danger-700"
                        title="删除任务"
                      >
                        <TrashIcon className="h-5 w-5" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-12">
              <ClipboardDocumentListIcon className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">暂无任务</h3>
              <p className="mt-1 text-sm text-gray-500">开始创建您的第一个任务吧！</p>
              <div className="mt-6">
                <Link to="/tasks/new" className="btn-primary">
                  创建任务
                </Link>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Tasks;
